<template>
  <div>
    <DynamicList
      ref="userListTable"
      v-bind="userListColumns"
      @load-data="setPage"
      @reset-data="onResetData"
    >
      <template #searchQuery>
        <div class="inline-flex items-center">
          <div class="pr-8px">账号状态</div>
          <a-select
            v-model:value="queryData.status"
            class="min-w-150px"
            placeholder="请选择状态"
            :options="[
              {
                label: '正常',
                value: 1,
              },
              {
                label: '禁用',
                value: 2,
              },
            ]"
            allow-clear
          >
          </a-select>
        </div>
      </template>
      <template #tableTop>
        <a-space class="flex-wrap" size="small">
          <a-button
            v-if="$auth('system-user-add')"
            type="primary"
            @click="router.push('/system/user/userDetail')"
          >
            <PlusOutlined /> 新增
          </a-button>
        </a-space>
      </template>
    </DynamicList>
    <a-modal v-model:visible="updateData.visible" centered title="修改密码" :footer="null">
      <a-form :model="passwordModelForm" @finish="handleFinish">
        <a-form-item
          label="新密码"
          :label-col="labelCol"
          name="password"
          :rules="[{ required: true, message: '请输入新密码' }]"
        >
          <a-input-password v-model:value="passwordModelForm.password" placeholder="请输入新密码" />
        </a-form-item>
        <a-space class="w-full justify-center">
          <a-button type="primary" html-type="submit"> 确认修改 </a-button>
        </a-space>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="tsx">
  import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Avatar, message, Modal, Tag } from 'ant-design-vue';
  import DynamicList from '@/components/dynamicList/index.vue';
  import { disableUser, resetUserPassword, sysUserApi } from '@/api/system/user';
  import { encryptByMd5, publicPathUrl } from '@/utils/common';
  import { formatToDateTime } from '@/utils/dateUtil';
  import { RequestEnum } from '@/enums/httpEnum';
  import { ComponentsTypeEnum } from '@/enums/componentsEnum';
  import useRequestList from '@/hooks/useRequestList';
  import { verifyAuth } from '@/core/permission';

  defineOptions({
    name: 'userList',
  });
  const router = useRouter();
  const userListTable = ref<any>(null);
  const updateData = reactive({
    visible: false,
    passwordModelForm: {
      id: 0,
      password: '',
    },
    labelCol: { span: 6 },
  });
  const queryData = ref<any>({ status: null });
  const { passwordModelForm, labelCol } = toRefs(updateData);
  const { list, page, setPage, loading } = useRequestList({
    apiKey: sysUserApi.sysUserList,
    type: RequestEnum.GET,
  });
  const userListColumns = ref({
    columns: [
      {
        title: 'ID',
        width: 50,
        align: 'center',
        dataIndex: 'id',
      },
      {
        title: '头像',
        width: 80,
        align: 'center',
        dataIndex: 'avatar',
        customRender: ({ record }) => <Avatar src={publicPathUrl + record.avatar} />,
      },
      {
        title: '昵称',
        width: 120,
        align: 'center',
        dataIndex: 'nickname',
      },
      {
        title: '登录账号',
        width: 120,
        align: 'center',
        dataIndex: 'username',
        search: true,
        component: ComponentsTypeEnum.Input,
      },
      {
        title: '最后登录IP',
        width: 120,
        align: 'center',
        dataIndex: 'loginIp',
      },
      {
        title: '最后登录时间',
        width: 120,
        align: 'center',
        dataIndex: 'loginDate',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '创建时间',
        width: 120,
        align: 'center',
        dataIndex: 'createTime',
        customRender: ({ text }) => {
          return text ? formatToDateTime(text) : '-';
        },
      },
      {
        title: '账号状态',
        dataIndex: 'status',
        width: 100,
        align: 'center',
        customRender: ({ record }) => {
          const isEnable = record.status == 1;
          return <Tag color={isEnable ? 'success' : 'red'}>{isEnable ? '正常' : '禁用'}</Tag>;
        },
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'operation',
        align: 'center',
        fixed: 'right',
        actions: [
          {
            title: '编辑',
            vIf: verifyAuth('system-user-update'),
            onClick: (record) => {
              router.push(`/system/user/userDetail?id=${record.id}`);
            },
          },
          {
            title: '',
            vIf: verifyAuth('system-user-disable'),
            statusText: (record) => {
              return record?.status == 1 ? '禁用' : '恢复';
            },
            onClick: (record) => {
              disableConfirmUser(record);
            },
          },
          {
            title: '修改密码',
            vIf: verifyAuth('system-user-reset-password'),
            onClick: (record) => {
              updateData.visible = true;
              updateData.passwordModelForm.id = record.id;
            },
          },
        ],
      },
    ],
    pageParams: page,
    queryParamsSlots: queryData,
    list,
    loading,
  });

  const disableConfirmUser = async (record) => {
    Modal.confirm({
      title: record.status == 1 ? '确定禁用吗?' : '确定恢复吗?',
      icon: <ExclamationCircleOutlined />,
      centered: true,
      onOk: async () => {
        await disableUser(record.id).finally(
          userListTable.value && userListTable.value.resetFields(),
        );
      },
    });
  };

  const handleFinish = async (values) => {
    const res = await resetUserPassword({
      id: updateData.passwordModelForm.id,
      password: encryptByMd5(values.password),
    });
    if (res) {
      message.success('修改成功!');
      updateData.visible = false;
    }
  };

  const onResetData = (queryParams) => {
    queryData.value = {};
    setPage(queryParams);
  };
</script>

<style></style>
